import collections, struct
from .records import Blkno

geometry = collections.namedtuple("Geometry", [
    "total_blocks", "block_size", "indirect_density",
    "boot_start", "boot_blocks", "boot_end",
    "bitmap_start", "bitmap_blocks", "bitmap_end", "bitmap_density",
    "data_start", "data_blocks", "data_end"])

def calculate_geometry(block_count, block_size):
    blocks_left = block_count - 1 # boot block
    bitmap_blocks = 0
    data_blocks = 0
    bitmap_density = block_size * 8
    while blocks_left > 1:
        bitmap_blocks += 1
        blocks_left -= 1
        data_blocks += min(bitmap_density, blocks_left)
        blocks_left -= bitmap_density
    assert -bitmap_density < blocks_left <= 1
    geo = geometry(
        total_blocks=1+bitmap_blocks+data_blocks,
        block_size=block_size,
        indirect_density=block_size//struct.calcsize(Blkno),
        boot_start=0,
        boot_blocks=1,
        boot_end=1,
        bitmap_start=1,
        bitmap_blocks=bitmap_blocks,
        bitmap_end=1+bitmap_blocks,
        bitmap_density=bitmap_density,
        data_start=1+bitmap_blocks,
        data_blocks=data_blocks,
        data_end=1+bitmap_blocks+data_blocks)
    assert block_count - geo.total_blocks == 0, block_count
    return geo
